<template>
  <a-modal
    :maskClosable="maskClosable"
    title="添加应用资源"
    :width="600"
    :visible="visible"
    :confirm-loading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :labelCol="{ span: 6 }" :wrapperCol="{ span: 14 }" :form="form">
        <a-form-item label="应用名称">
          <a-input
            autocomplete="off"
            v-decorator="['name', decoratorOptions.name]"
          />
        </a-form-item>

        <!-- <a-form-item label="应用类型">
          <a-select
            :getPopupContainer="
              (triggerNode) => {
                return triggerNode.parentNode || document.body;
              }
            "
            v-decorator="['state', decoratorOptions.state]"
          >
            <a-select-option
              v-for="(item, index) in stateMap"
              :key="'state_' + index"
              :value="index"
            >
              {{ item }}
            </a-select-option>
          </a-select>
        </a-form-item> -->

        <a-form-item label="数据中心">
          <a-select
            :getPopupContainer="
              (triggerNode) => {
                return triggerNode.parentNode || document.body;
              }
            "
            v-decorator="['datacenterId', decoratorOptions.datacenterId]"
            @change="handleDatacenterChange"
          >
            <a-select-option
              v-for="d in datacenterList"
              :key="d.id"
              :value="d.id"
            >
              {{ d.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="云平台资源">
          <a-select
            :getPopupContainer="
              (triggerNode) => {
                return triggerNode.parentNode || document.body;
              }
            "
            v-decorator="['resourceId', decoratorOptions.resourceId]"
            @change="handleCloudresourceChange"
          >
            <a-select-option
              v-for="(item, index) in resourceList"
              :key="'resourceId_' + index"
              :value="item.id"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="应用实例" :wrapperCol="{ span: 18 }">
          <a-checkbox-group
            :options="options"
            v-decorator="['checkedList', decoratorOptions.checkedList]"
          />
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>
<script>
import { gPostAction, getAction } from "@/api/manage";
export default {
  name: "AddModal",
  data() {
    return {
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      resourceList: [],
      decoratorOptions: {
        name: {
          rules: [
            { required: true, message: "请输入应用名称" },
            { validator: this.validators.noWhitespace() },
            { validator: this.validators.noIllegalString() },
            { max: 10, message: "长度在 1 到 10 个字符", trigger: "blur" },
          ],
        },
        state: {
          initialValue: 0,
          rules: [{ required: true, message: "请选择应用类型" }],
        },
        datacenterId: {
          rules: [{ required: true, message: "请选择数据中心" }],
        },
        resourceId: {
          rules: [{ required: true, message: "请选择云平台资源" }],
        },
        checkedList: {
          initialValue: [],
          rules: [
            {
              required: true,
              message: "请选择应用资源",
            },
          ],
        },
      },
      stateMap: ["无状态", "有状态"],
      options: [],
      datacenterList: [],
      maskClosable: false,
    };
  },
  methods: {
    add() {
      this.visible = true;
      this.form.resetFields();
      this.loadDatacenterList();
    },
    loadDatacenterList() {
      gPostAction("/asset/pageDatacenter", { pageSize: 99 }).then((res) => {
        this.datacenterList = res.data.list;
        if (this.datacenterList && this.datacenterList.length) {
          const item = this.datacenterList[0];

          this.form.setFieldsValue({
            datacenterId: item.id,
          });
          this.loadResourceList(item.id);
        }
      });
    },
    loadResourceList(id) {
      this.resourceList = [];
      this.options = [];
      this.form.setFieldsValue({
        resourceId: "",
        checkedList: [],
      });

      const postData = {
        pageSize: 99,
        datacenterId: id,
      };

      gPostAction("/cloud_resource/page", postData).then((res) => {
        if (res.success) {
          this.resourceList = res.data.list;
          if (this.resourceList && this.resourceList.length) {
            this.form.setFieldsValue({
              resourceId: res.data.list[0].id,
            });
            this.loadNamespacesList(res.data.list[0].id, id);
          }
        }
      });
    },
    loadNamespacesList(cId, dId) {
      this.options = [];
      this.form.setFieldsValue({
        checkedList: [],
      });
      if (!dId) {
        dId = this.form.getFieldValue("datacenterId");
      }
      if (dId && cId) {
        this.options = [];
        getAction("/app/queryNamespaceList", {
          datacenterId: dId,
          cloudResourceId: cId,
        }).then((res) => {
          if (res.success && res.data) {
            res.data.forEach((d) => {
              this.options.push({
                label: d.name,
                value: d.id,
              });
            });
          }
        });
      }
    },
    handleDatacenterChange(value) {
      if (value) {
        this.loadResourceList(value);
      }
    },
    handleCloudresourceChange(value) {
      if (value) {
        this.loadNamespacesList(value);
      }
    },
    handleOk(e) {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true;

          let postData = {
            name: values.name,
            type: values.state,
            cloudResourceId: values.resourceId,
            title:
              "精确管控与供电制冷联动-基础资源细粒度感知-资源管理-L4层：应用资源",
          };
          const list = values.checkedList;
          let mark = 0;
          if (list && list.length) {
            this.options.forEach((opt) => {
              if (list.indexOf(opt.value) > -1) {
                postData["instances[" + mark + "].instanceId"] = opt.value;
                postData["instances[" + mark + "].instanceName"] = opt.label;
                mark++;
              }
            });
          }
          gPostAction("/app/create", postData)
            .then((res) => {
              if (res.success) {
                this.$message.success("操作成功");
                this.$emit("ok");
              }
            })
            .finally(() => {
              this.handleCancel();
            });
        }
      });
    },
    handleCancel() {
      this.visible = false;
      this.confirmLoading = false;
    },
  },
};
</script>
